const { DataSystemUserModel } = require("../models/sys_user");
const {
  getUserDataFromRedis,
  setDataScopeToRedis,
} = require("../utils/userRedis");
const { fail, CODE } = require("../utils/utils");

module.exports = async (ctx, next) => {
  try {
    const { user = {} } = ctx.state;
    const userData = await getUserDataFromRedis(user.user_id);
    if (!userData || !userData.role_info) {
      return (ctx.body = fail(null, "权限禁止", CODE.AUTH_ERROR));
    }
    const { role_info } = userData;
    const role_data_scope = role_info.filter((item, index, arr) => {
      return arr.findIndex(obj => obj.data_scope === item.data_scope) === index
    });
    let allDataScope = role_data_scope.find(item => item.data_scope === '1');
    let sql = "";
    if (!allDataScope) {
      // 获取所有数据权限
      for (let index = 0; index < role_data_scope.length; index++) {
        const element = role_data_scope[index];
        switch (element.data_scope) {
          // 获取自定义数据权限
          case "2":
            let {result:custom_user_info} = await DataSystemUserModel.getUserIdByRoleId(
              element.role_id
            );
            let custom_ids = custom_user_info.map((item) => {
              return item.user_id;
            });
            sql = `and create_by in (${custom_ids.join(",")}) `;
            break;
          // 获取当前部门数据权限
          case "3":
            let dept_user_info = await DataSystemUserModel.getUserIdByDeptId(
              dept_id
            );
            let dept_user_ids = dept_user_info.map((item) => {
              return item.user_id;
            });
            sql = `and create_by in (${dept_user_ids.join(",")}) `;
            break;
          // 获取当前部门及子部门数据权限
          case "4":
            let dept_all_user_info =
              await DataSystemUserModel.getUserIdByDeptTreeId(dept_id);
            let dept_all_user_ids = dept_all_user_info.map((item) => {
              return item.user_id;
            });
            sql = `and create_by in (${dept_all_user_ids.join(",")}) `;
            break;
          // 获取本人数据权限
          case "5":
            sql = `and create_by in (${user.user_id}) `;
            break;
          default:
            break;
        }
      }
    }
    ctx.state.data_scope = sql || ''
    return next();
  } catch (error) {
    return ctx.body = fail(null, error.message, CODE.BUSINESS_ERROR);
  }
};
